package com.eight.cloud.core.utils.HttpUtils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.eight.cloud.core.utils.format.ObjectFormat;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.SortedMap;
import java.util.TreeMap;

import static com.eight.cloud.core.global.constant.NumConstant.ONE;
import static com.eight.cloud.core.global.constant.NumConstant.ZERO;
import static com.eight.cloud.core.global.constant.StrConstant.*;
import static com.eight.cloud.core.utils.format.ObjectFormat.*;

/**
 * @ClassName: HttpUtils
 * @Author: TXC
 * @Date: 2024-10-22 16:19
 **/
public class HttpRequestUtils {
    /**
     * 获取请求URI
     * @return 获取请求URI
     */
    public static String getPermissionsCode(String module) {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if (ObjectUtil.isNotNull(request)) {
            String pathInfo = request.getRequestURI();
            String method = request.getMethod();
            return module + pathInfo.replace(SLASH, COLON) + COLON + method.toLowerCase();
        }
        return null;
    }

    /**
     * post请求处理：获取 Body 参数，转换为SortedMap
     *
     * @param request
     */
    public static SortedMap<String, Object> getBodyParams(final HttpServletRequest request) throws IOException {
        byte[] requestBody = StreamUtils.copyToByteArray(request.getInputStream());
        return ObjectFormat.byteToObj(SortedMap.class, requestBody);
    }


    /**
     * get请求处理：将URL请求参数转换成SortedMap
     */
    public static SortedMap<String, Object> getUrlParams(final HttpServletRequest request) {
        String param = "";
        SortedMap<String, Object> result = new TreeMap<>();

        if (StrUtil.isEmpty(request.getQueryString())) {
            return result;
        }
        param = URLDecoder.decode(request.getQueryString(), StandardCharsets.UTF_8);
        String[] params = param.split(AMPERSAND);
        for (String s : params) {
            String[] array=s.split(EQUAL);
            result.put(array[ZERO], array[ONE]);
        }
        return result;
    }

    public static String getRequestParams(final HttpServletRequest request) throws IOException {
        String method = request.getMethod();
        if (StrUtil.equalsIgnoreCase(method, POST)) {
            return objectToStr(getBodyParams(request));
        } else if (StrUtil.equalsIgnoreCase(method, GET)) {
            return objectToStr(getUrlParams(request));
        } else {
            return null;
        }
    }
}
